<!--
 * @Author: Junxu
 * @Date: 2024-04-01 16:30:38
 * @LastEditors: Junxu
 * @LastEditTime: 2024-04-11 11:45:52
 * @Description: 通知列表
-->
<template>
	<ui-container :scrollGoTop="0" :full="true" :scrollbar="false">
		<view class="my_wrapper">
			<view class="wrapper">
				<view class="item_search">
					<view class="search-bar">
						<uni-search-bar class="uni-search-bar" v-model="keywords" clearButton="auto" cancelButton="none"
							placeholder="搜索" @blurs="searchInput" />
					</view>
				</view>
			</view>
			<scroll-view scroll-x="true" class="scroll-x">
				<view class="tabList">
					<view v-for="(item, index) in tabList"
						:class="['titleTab', tabStateIdx == index ? 'activeItem' : '']" @click="chooseTab(item, index)"
						:key="index">
						{{ item.name }}
						<view class="badge" v-if="item.badge">{{ item.badge }}</view>
					</view>
				</view>
			</scroll-view>
			<view class="msgAll">
				<view class="msg-all-btn" @click="setMsgReadAll">
					<image :src="`../../static/images/${tabList[tabStateIdx].badge ? 'msgAll' : 'msgNone'}.png`"
						mode=""></image>
					<text :style="{ color: tabList[tabStateIdx].badge ? '#0091FF' : '#B0B7BC' }">全部已读</text>
				</view>
			</view>
			<view class="item_content">
				<scroll-view class="scrollBox" :scroll-y="true" :refresher-enabled="isAllowRefresh"
					:refresher-triggered="triggered" scroll-with-animation @scrolltolower="scrolltolower"
					@refresherrefresh="onRefresh" @scroll="scroll" :scroll-top="scrollGoTop">
					<view>
						<!-- S-离线提醒 -->
						<view class="offline-tips" v-if="offline">
							<image src="@/static/images/reload.png"> </image>
							当前网络离线，下拉刷新列表
						</view>
						<!-- E-离线提醒 -->

						<!-- S-通知列表 -->
						<view class="notice-main" v-if="list && list.length">
							<view class="notice-card" v-for="(item, i) in list" :key="item.id"
								@click.native="viewDetail(item, i)" :style="{ marginTop: i === 0 ? '0' : '20rpx' }">
								<view class="notice-card-image" :style="{
									backgroundColor: item.isRead == 1 ? '#CCCCCC' : '#dcf0ff',
								}">
									<image :src="`../../static/images/index/${item.isRead == 1 ? 'emailGrey' : 'emailBlue'
										}.png`" mode="">
									</image>
								</view>
								<view class="notice-card-body">
									<view class="notice-card-header">
										<view class="notice-card-title">{{ item.title }}</view>
										<view class="notice-card-time">{{ item.createTime }}</view>
									</view>
									<view class="notice-card-content">{{
										item.contentText
									}}</view>
								</view>
							</view>
							<uni-load-more v-if="isStateMore" :status="state"
								:contentText="contentText"></uni-load-more>
						</view>
						<!-- E-通知列表 -->

						<!-- S-暂无数据 -->
						<view class="empty" v-else>
							<image src="../../static/images/index/empty1.png" mode=""></image>
							暂无数据
						</view>
						<!-- E-暂无数据 -->
					</view>
				</scroll-view>
			</view>
			<!-- <view-top ref="viewTop" :scrollTop="scrollTop" :distance="100" @goTop="goTop"></view-top> -->
		</view>
	</ui-container>
</template>

<script>
import { getUserNoticeList, getUserNoticeDetail, getUserMsgPage, setMsgReadOne, getUnreadCount, setMsgReadAll, setUsernoticeReadAll } from '@/apis/notice.js';

import dayjs from 'dayjs';
export default {
	name: 'Notice',
	data() {
		return {
			tabStateIdx: 0,
			tabList: [
				{
					name: '工单',
					status: 1,
					badge: 0,
				},
				{
					name: '系统',
					status: 2,
					badge: 0,
				},
			],
			// 网络离线
			offline: false,
			// 列表数据
			list: [],
			// 返回顶部
			scrollGoTop: 0,
			// 滚动距离
			scrollTop: 0,
			scrollsettingHight: 0,
			isAllowRefresh: true,
			triggered: false,
			pages: {
				current: 1,
				size: 10,
			},
			totalPages: 0,
			totalCount: 0,
			contentText: {
				contentdown: '上拉显示更多',
				contentrefresh: '正在加载...',
				contentnomore: '没有更多了',
			},
			state: '',
			// 只有一页数据隐藏更多显示
			isStateMore: false,
			keywords: '',
			allLoading: false,
		};
	},
	created() {
		this.getData();
	},
	onShow() {
		this.getUnreadCount();
	},
	onUnload() {
		console.log('onUnload-refreshUnreadCount');
		// eslint-disable-next-line vue/custom-event-name-casing
		uni.$emit('refreshUnreadCount');
	},
	methods: {
		// 全部已读
		async setMsgReadAll() {
			if (this.tabList[this.tabStateIdx].badge == 0) return;
			if (this.allLoading) return;
			this.allLoading = true;
			uni.showLoading({
				title: '加载中'
			});
			const apis = [setMsgReadAll, setUsernoticeReadAll];
			try {
				await apis[this.tabStateIdx](/* 可传参数 */);
				this.pages.current = 1;
				this.list = [];
				await this.getData();
				await this.getUnreadCount();
				this.allLoading = false;
				uni.hideLoading();
			} catch (error) {
				this.allLoading = false;
				uni.hideLoading();
				console.error('全部已读失败:', error);
			}
		},
		// 状态切换筛选
		chooseTab(item, index) {
			this.goTop();
			this.tabStateIdx = index;
			this.onRefresh();
		},
		// 搜索
		searchInput(val) {
			console.log(val, 'search-res');
			this.pages.current = 1;
			this.list = [];
			this.keywords = val;
			this.getData();
		},
		goTop() {
			this.scrollGoTop = 1;
			this.$nextTick(() => {
				this.scrollGoTop = 0;
			});
		},
		scroll(e) {
			this.scrollTop = e.target.scrollTop;
			if (e.target.scrollTop > 100) {
				this.isAllowRefresh = false;
			} else {
				this.isAllowRefresh = true;
			}
		},
		// 下拉控件触发
		onPulling() {
			this.triggered = true;
		},
		// 下拉触发
		onRefresh() {
			console.log('下拉刷新');
			this.triggered = true;
			this.pages.current = 1;
			this.list = [];
			this.getData();
		},
		// 下拉加载
		scrolltolower() {
			if (this.pages.current * this.pages.size < this.totalCount) {
				this.pages.current += 1;
				this.getData();
			} else {
				this.state = 'noMore';
			}
		},
		// 查询通知列表未读数量
		async getUnreadCount() {
			console.log('看看消息查询数据');
			try {
				const res = await getUnreadCount();
				const res2 = await getUserMsgPage({ current: 1, size: 10, typeIds: '14,21', status: 1 });
				console.log(res, 'res');

				if (res && res.code === 200) {
					this.tabList[1].badge = res.data;
				}
				if (res2 && res2.code === 200) {
					console.log(res2, 'getUserMsgPage');
					this.tabList[0].badge = res2.data.total;
				}
			} catch (error) {
				console.log(error);
			}
		},
		// 获取数据
		async getData() {
			console.log('getData');
			this.state = 'loading';
			try {
				const params = {
					title: this.keywords,
					keyword: this.keywords,
					...this.pages,
				};
				let request = getUserMsgPage;
				if (this.tabStateIdx === 1) {
					request = getUserNoticeList;
				} else {
					params.typeIds = '14,21';
				}
				const res = await request(params);
				console.log(res, '消息数据');
				if (res.code === 200) {
					let recordList = res.data.records || [];
					if (this.tabStateIdx === 1) {
						recordList.forEach((v) => {
							v.contentText = v.content
								.replace(/<[^>]*>/g, '')
								.replace(/&nbsp;/g, '');
						});
					} else {
						recordList.forEach((v) => {
							v.contentText = v.content;
							v.isRead = (v.status === 1 ? 0 : 1);
						});
					}
					if (recordList.length > 0) {
						this.totalCount = res.data.total;
						this.totalPages = res.data.pages;
						let orginList = this.list;
						this.list = orginList.concat(recordList);
					} else {
						this.state = 'noMore';
					}
					this.triggered = false;
					this.isStateMore = res.data.pages !== 1;
				}
			} catch (error) {
				this.triggered = false;
				this.offline = true;
			}
		},
		// 处理未读信息
		async getDetail(id) {
			this.loading = true;
			uni.showLoading({
				title: '加载中'
			});
			try {
				let request = setMsgReadOne;
				let params = { id };
				if (this.tabStateIdx === 1) {
					request = getUserNoticeDetail;
					params = { noticeId: id };
				}
				const res = await request(params);
				await this.getUnreadCount();
				console.log(res, 'res');
				// if (res && res.code == 200) {
				// 	if (res.data) {
				// 		this.info = {
				// 			...res.data,
				// 			content: parseHtml(this.formatRichText(res.data.content))
				// 		};
				// 		this.errorStatus = res.data.isDeleted == 1 ? 2 : 0;
				// 	} else {
				// 		this.errorStatus = 2;
				// 	}
				// } else if (res && res.code == 400) {
				// 	this.errorStatus = 1;
				// }
				// this.loading = false;
				// uni.hideLoading();
			} catch (error) {
				// this.errorStatus = 1;
				// this.loading = false;
				// uni.hideLoading();
				console.log(error);
			}
		},
		// 查看详情
		viewDetail(item, index) {
			// 救援
			if (item.type == '21') {
				uni.navigateTo({
					url: `/subpages/rescue/rescueDetail?planId=${item.otherId}&elevatorId=${item.elevatorId}`
				});
				return;
			}
			// 如果是排班
			if (this.tabStateIdx === 1) {
				if (item.category == 10) {
					let month = '';
					let year = '';
					if (item.signDate == null) {
						year = dayjs(new Date()).year();
						month = dayjs(new Date()).month() + 1;

						console.log(month);
					} else {
						year = item.signDate.slice(0,4);
						month = dayjs(item.signDate.slice(0,10)).month() + 1;

						console.log(year,month);
					}
					if (item.isRead === 0) {
						this.getDetail(item.id);
						this.list[index].isRead = 1;
					}
					uni.navigateTo({
						url: `/ pageModules / signPage / siginIndex ? month = ${ month } & duty=true & year=${ year }`
					});
				} else {
					if (item.isRead === 0) {
						this.getDetail(item.id);
						this.list[index].isRead = 1;
					}
					// return;
					uni.navigateTo({
						url: `/ subpages / notice / detail ? id = ${ item.id }`,
					});
				}
			} else {
				console.log(item,'item');
				let urlQuery = '';
				if (item.isRead === 0) {
					this.getDetail(item.id);
					this.list[index].isRead = 1;
				}
				if (item.title.indexOf('签字通知') !== -1) {
					urlQuery = '&statusStr=3&auditTypeStr=2&userSignatureType=1';
				} else if (item.title.indexOf('保养未完成') !== -1) {
					urlQuery = `& statusStr=${ [1, 2, 3].join() } & overdueTypeStr=3 & auditTypeStr=2`;
				} else if (item.title.indexOf('明天') !== -1) {
					urlQuery = '&auditTypeStr=2&overdueTypeStr=2';
				}
				uni.navigateTo({
					url: `/ subpages / workOrders / records ? type = 2 & tabIndex=0${ urlQuery }`
				});
			}
		},
	},
};
</script>

<style scoped lang="scss">
.my_wrapper {
	background-color: #f3f6f8;
	min-height: 100vh;

	.empty {
		display: flex;
		justify-content: center;
		width: 100%;

		image {
			width: 64rpx;
			height: 64rpx;
			margin-bottom: 20rpx;
		}

		color: #999;
		flex-direction: column;
		align-items: center;
		padding-top: 300rpx;
		font-size: 24rpx;
	}
}

.search-bar {
	width: 100vw;
	box-sizing: border-box;
	background: #ffffff;
	display: flex;
	align-items: center;
	justify-content: center;
	height: 110rpx;
	overflow: hidden;
	box-sizing: border-box;

	.uni-search-bar {
		/deep/ .uni-searchbar {
			width: 100%;
			padding: 0;
		}

		/deep/ .uni-searchbar__box {
			height: 76rpx;
			width: calc(100vw - 40rpx);
			justify-content: flex-start;
			font-size: 26rpx;
			color: #ccc;
			background-color: #f6f6f6;
			border: 0;
			border-radius: 8rpx;
		}

		/deep/ .uni-searchbar__box-icon-search {
			width: 70rpx;
		}

		/deep/ .uni-icons {
			font-size: 36rpx !important;
		}

		/deep/ .uni-searchbar__text-placeholder {
			margin: 0;
		}

		/deep/ .uni-searchbar__box-search-input {
			height: 80rpx;
		}

		/deep/ .uni-searchbar__box-search-input {
			border: 0;
			padding: 0;
		}
	}

	image {
		width: 40rpx;
		height: 40rpx;
	}
}

.scrollBox {
	height: calc(100vh - 198rpx);
}

.notice-main {
	padding-bottom: 40rpx;
}

.notice-card {
	margin-top: 20rpx;
	display: flex;
	align-items: center;
	padding: 30rpx 20rpx;
	font-size: 28rpx;
	background-color: #ffffff;
	color: #333333;

	&-image {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 96rpx;
		height: 96rpx;
		background: #dcf0ff;
		border-radius: 50%;

		image {
			width: 64rpx;
			height: 64rpx;
		}
	}

	&-body {
		flex: 1;
		width: 0;
		padding-left: 20rpx;
	}

	&-header {
		display: flex;
		align-items: center;
		padding-bottom: 16rpx;
	}

	&-title {
		font-size: 32rpx;
		flex: 1;
		width: 0;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	&-time {
		font-size: 24rpx;
		color: #999999;
		padding-left: 20rpx;
	}

	&-content {
		width: 100%;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
}

.offline-tips {
	color: #999999;
	font-size: 24rpx;
	text-align: center;
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	padding-top: 20rpx;

	image {
		width: 32rpx;
		height: 32rpx;
	}
}

.tabList {
	display: flex;
	padding: 20rpx 0;
	background-color: #FFFFFF;
	border-top: 2rpx solid #EEEEEE;
	border-bottom: 2rpx solid #EEEEEE;

	.titleTab {
		position: relative;
		height: 44rpx;
		border-radius: 22rpx;
		padding: 0 20rpx;
		margin-left: 20rpx;
		background-color: #F3F6F8;
		color: #666;
		font-size: 26rpx;
		line-height: 44rpx;
	}

	.activeItem {
		background-color: #DCF0FF;
		color: #0091FF;
		font-size: 26rpx;
	}

}

.msgAll {
	font-size: 28rpx;
	height: 80rpx;
	color: #0091FF;

	.msg-all-btn {
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: flex-end;
		margin-right: 20rpx;
	}

	image {
		width: 32rpx;
		height: 32rpx;
	}
}

.badge {
	position: absolute;
	right: -10rpx;
	top: -10rpx;
	min-width: 32rpx;
	height: 32rpx;
	background: #e02020;
	border-radius: 32rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 20rpx;
	color: #fff;
	margin-left: 10px;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}
</style>
